package main

import (
	"flag"
	"fmt"
	"runtime"
	"time"

	"github.com/spf13/viper"
)

var (
	conf     *Config
	confPath string
)

func init() {
	flag.StringVar(&confPath, "d", "./logic/", " set logic config file path")
}

type Config struct {
	Base BaseConf `mapstructure:"base"`
	//Bucket    BucketConf    `mapstructure:"bucket"`
}

// BaseConf 基础的配置信息
type BaseConf struct {
	Pidfile          string `mapstructure:"pidfile"`
	MaxProc          int
	PprofAddr        string        `mapstructure:"pprofBind"` //
	HttpAddr         string        `mapstructure:"httpAddr"`  //
	RedisAddr        string        `mapstructure:"RedisAddr"` //
	RedisPw          string        `mapstructure:"redisPw"`
	RedisDefaultDB   int           `mapstructure:"redisDefaultDB"`
	RPCAddr          string        `mapstructure:"RPCAddr"` //
	HTTPReadTimeout  time.Duration `mapstructure:"HTTPReadTimeout"`
	HTTPWriteTimeout time.Duration `mapstructure:"HTTPWriteTimeout"`
}

func InitConfig() (err error) {
	conf = NewConfig()
	viper.SetConfigName("logic")
	viper.SetConfigType("toml")
	viper.AddConfigPath(confPath)

	if err = viper.ReadInConfig(); err != nil {
		return err
	}

	if err = viper.Unmarshal(&conf); err != nil {
		panic(fmt.Errorf("unable to decode into struct：  %s \n", err))
	}

	return nil
}

func NewConfig() *Config {
	return &Config{
		Base: BaseConf{
			Pidfile:          "/tmp/logic.pid",
			MaxProc:          runtime.NumCPU(),
			PprofAddr:        "localhost:6922",
			HttpAddr:         "localhost:6921",
			RedisAddr:        "192.168.51.138:6379",
			RedisPw:          "",
			RedisDefaultDB:   0,
			RPCAddr:          "tcp@localhost:6923",
			HTTPReadTimeout:  10 * time.Second,
			HTTPWriteTimeout: 20 * time.Second,
		},
	}
}

// 重新加载配置
// func ReloadConfig() {
//
// }
